package com.lv.common.base

import android.content.Context
import androidx.annotation.NonNull
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.lv.common.R
import com.lv.common.network.OkHttpApi
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.io.IOException
import java.io.InputStream
import java.util.concurrent.TimeUnit

/**
 * 作者： ygx
 * 创建日期：2023/3/31 9:15 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：Glide 策略
 */
@GlideModule
class MyAppGlideModule : AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //设置磁盘缓存策略  最大缓存100MB
        builder.setDiskCache(
            InternalCacheDiskCacheFactory(
                context, "glide_cache", 100 * 1024 * 1024
            )
        )
        val options = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)//使用所有策略缓存
            .placeholder(R.drawable.icon_logo_gray).error(R.drawable.icon_logo_gray)
        builder.setDefaultRequestOptions(options)
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)

        // 替换底层网络框架为okhttp3
//        registry.replace(
//            GlideUrl::class.java,
//            InputStream::class.java, OkHttpUrlLoader.Factory(OkHttpApi.getInstance().getClient())
//        )
    }
}

//@GlideModule
//class MyAppGlideModule : AppGlideModule() {
//
//    companion object {
//        private const val MAX_RETRIES = 3 // 最大重试次数
//        private const val RETRY_DELAY_MS: Long = 1000 // 每次重试的延迟时间（毫秒）
//    }
//
//    override fun applyOptions(@NonNull context: Context, @NonNull builder: GlideBuilder) {
//        //设置磁盘缓存策略  最大缓存100MB
//        builder.setDiskCache(
//            InternalCacheDiskCacheFactory(
//                context, "glide_cache", 100 * 1024 * 1024
//            )
//        )
//        val options = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)//使用所有策略缓存
//            .placeholder(R.drawable.icon_logo_gray).error(R.drawable.icon_logo_gray)
//        builder.setDefaultRequestOptions(options)
//    }
//
//    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
//        val okHttpClient = createCustomOkHttpClient()
//        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(okHttpClient))
//    }
//
//    private fun createCustomOkHttpClient(): OkHttpClient {
//        return OkHttpClient.Builder()
//            .connectTimeout(30, TimeUnit.SECONDS)
//            .readTimeout(30, TimeUnit.SECONDS)
//            .writeTimeout(30, TimeUnit.SECONDS)
//            .addInterceptor(RetryInterceptor(MAX_RETRIES, RETRY_DELAY_MS))
//            .build()
//    }
//
//    // 自定义拦截器，用于处理重试逻辑
//    class RetryInterceptor(private val maxRetries: Int, private val retryDelayMillis: Long) :
//        Interceptor {
//        override fun intercept(chain: Interceptor.Chain): Response {
//            val request = chain.request()
//            var response: Response? = null
//            var exception: IOException? = null
//
//            for (attempt in 0..maxRetries) {
//                try {
//                    LogUtils.e("RetryInterceptor", "Attempt ${attempt + 1} for URL: ${request.url}")
//                    response = chain.proceed(request)
//                    if (response.isSuccessful) {
//                        return response
//                    }
//                } catch (e: IOException) {
//                    exception = e
//                    LogUtils.e("RetryInterceptor", "Request failed: ${e.message}")
//                }
//
//                // 如果响应码是404，不进行重试
//                if (response != null && response.code == 404) {
//                    LogUtils.e("RetryInterceptor", "Received 404, no retry for URL: ${request.url}")
//                    break
//                }
//
//                // 如果已经达到最大重试次数，跳出循环
//                if (attempt == maxRetries) {
//                    LogUtils.e("RetryInterceptor", "Max retries reached for URL: ${request.url}")
//                    break
//                }
//
//                // 延迟一段时间后重试
//                try {
//                    Thread.sleep(retryDelayMillis)
//                } catch (e: InterruptedException) {
//                    Thread.currentThread().interrupt()
//                    throw IOException("Retry interrupted", e)
//                }
//            }
//
//            // 如果达到最大重试次数仍未成功，抛出异常或返回失败的响应
//            return response ?: throw exception ?: IOException("Unknown error")
//        }
//    }
//}
